import React, { useRef, useState, useEffect } from 'react'
import { Modal, Form, Input, Select, Cascader, Button, Upload, message } from 'antd'
import Dictionary from '@js/dictionary'
import { getProvinceCityTree } from '@js/area'
import { UploadOutlined } from '@ant-design/icons'
import { awaitWrap, getUploadPropsFn } from '@js/tool'
import { submitFiles } from '@js/request'
import { addRequest, getRequest, updateRequest } from './ajax'

const areas = getProvinceCityTree()
const { Item } = Form
const { Option } = Select
const { TextArea } = Input

async function getHandle (id, formRef, setFileList) {
  const c = formRef.current
  const h = message.loading('加载中')
  const [e, d] = await awaitWrap(getRequest(id))
  h()
  if (e === null && d !== null) {
    if (d.area) {
      d.area = d.area.split(',')
    }
    if (d.file instanceof Array && d.file.length > 0) {
      setFileList(d.file.map(li => {
        li.name = li.original_filename || li.filename
        return li
      }))
    }
    c.setFieldsValue(d)
  }
}

async function submitHandle (form, fileList, callback) {
  const hide = message.loading('提交中', 120)
  let fn = addRequest
  if (form.id) {
    fn = updateRequest
  }
  if (fileList.length > 0) {
    const [e, d] = await awaitWrap(submitFiles(fileList))
    if (e) {
      hide()
    }
    form.fileid = d
  }
  delete form.file
  if (form.area instanceof Array) {
    form.area = form.area.join()
  }
  const [e] = await awaitWrap(fn(form))
  hide()
  if (e === null) {
    callback()
  }
}

function Main ({ visible, data, hide = () => {}, refreshFn = () => {} }) {
  const formRef = useRef(null)
  const [types, setTypes] = useState([])
  const [fileList, setFileList] = useState([])
  const [statusList, setStatusList] = useState([])
  useEffect(() => {
    const d = new Dictionary()
    d.init('鉴定机构类别,鉴定机构状态')
      .then(() => {
        setTypes(d.getList('鉴定机构类别'))
        setStatusList(d.getList('鉴定机构状态'))
      })
  }, [])
  useEffect(() => {
    const c = formRef.current
    if (c) {
      if (visible) {
        if (data) {
          getHandle(data.id, formRef, setFileList)
        }
      } else {
        setFileList([])
        c.resetFields()
      }
    }
  }, [visible, data, formRef])
  return (
    <Modal width='600px' open={visible} title={`${data ? '编辑机构' : '新增机构'}`} onCancel={() => { hide() }} onOk={() => formRef.current.submit()}>
      <Form ref={formRef} labelCol={{ flex: '140px' }} onFinish={(d) => { submitHandle(d, fileList, () => { refreshFn(); hide() }) }}>
        <Item name='id' noStyle><span /></Item>
        <Item label='鉴定机构名称' name='name' rules={[{ required: true, message: '机构名称不能为空' }]}>
          <Input placeholder='请输入' allowClear />
        </Item>
        <Item label='鉴定机构类别' name='type'>
          <Select placeholder='请选择' allowClear>
            {
              types.map((li, i) => {
                return <Option value={li.value} key={i}>{li.value}</Option>
              })
            }
          </Select>
        </Item>
        <Item label='资质' name='qualification'>
          <Input placeholder='请输入' allowClear />
        </Item>
        <Item label='资质证书' name='qualification_certificate'>
          <Input placeholder='请输入' allowClear />
        </Item>
        <Item label='负责人/法定代表人' name='legal'>
          <Input placeholder='请输入' allowClear />
        </Item>
        <Item label='联系人' name='contact'>
          <Input placeholder='请输入' allowClear />
        </Item>
        <Item label='联系电话' name='tel'>
          <Input placeholder='请输入' allowClear />
        </Item>
        <Item label='省市' name='area'>
          <Cascader options={areas} placeholder='请选择' />
        </Item>
        <Item label='地址' name='address'>
          <TextArea placeholder='请输入' allowClear />
        </Item>
        <Item label='主管单位' name='p_structure'>
          <Input placeholder='请输入' allowClear />
        </Item>
        <Item label='备注' name='remark'>
          <TextArea placeholder='请输入' allowClear />
        </Item>
        <Item name='file' label='附件材料'>
          <Upload {...getUploadPropsFn.call(this, formRef, '.png,.jpg,.jpeg,.pdf', fileList, setFileList)}>
            <Button>
              <UploadOutlined /> 上传文件
            </Button>
          </Upload>
        </Item>
        <Item label='鉴定机构状态' name='status' rules={[{ required: true, message: '鉴定机构状态不能为空' }]}>
          <Select placeholder='请选择' allowClear>
            {
              statusList.map((li, i) => {
                return <Option value={parseInt(li.value)} key={i}>{li.title}</Option>
              })
            }
          </Select>
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
